<?php
namespace app\frontend\controller;
use \think\Db;
use \think\Validate;
use think\Controller;
class Changepwd extends Controller
{
    public function index()
    {
        if(!session('user_name'))
        {
            $user_name='登录';
            $user_register='注册';
            $user_logout='';
        }
        else
        {
        $user_name=session('user_name');
        $user_register='欢迎你';
        $user_logout='退出';
        }

        $this->assign('user_name',$user_name);
        $this->assign('user_register',$user_register);
        $this->assign('user_logout',$user_logout);
    	return view('./person/changepwd');
    }
    public function changepwd()
    {
    	if(request()->isPost())
       {
        
        $user_origin_password = input('post.user-old-password');
        $user_new_password = input('post.user-new-password');
        $user_confirm_password = input('post.user-confirm-password');
        
        
        $rule = [
            'user_origin_password'  => 'require',
            'user_new_password' => 'require|min:6|max:30',
            'user_confirm_password' => 'require|confirm:user_new_password'
        ];
        $msg = [
            'user_origin_password.require'  => '修改密码前请输入原密码！',
            'user_new_password.require' => '请输入新密码',
            'user_new_password.min' => '密码长度最小为6位',
            'user_new_password.max' => '密码长度最多为30位',
            'user_confirm_password.require'  => '请确认密码！',
            'user_repwd.confirm' => '两次密码不一致'
            
        ];

        $data = [
            'user_origin_password' => $user_origin_password,
            'user_new_password'    =>  $user_new_password,
            'user_confirm_password'  =>  $user_confirm_password   
        ];
        $validate = new Validate($rule, $msg);
        $result   = $validate->check($data);
        if (!$result ) {
            $this->error($validate->getError());
        }

       /*控制登录密码必须有数字和字母组成 */
        if(preg_match("/[A-Za-z]/",$user_new_password)&preg_match("/\d/",$user_new_password))
        {}
        else
        {
            $this->error("密码必须由数字和字母组成");
         }
         

         $data = [  
            'user_pwd' =>  md5($user_new_password)  
        ];

        $user_id = input('session.user_id');
        
        
        
        $user_info = db('user')->where('user_id', $user_id) ->value('user_pwd');
         
         if($user_info != md5($user_origin_password))
         {
            $this->error("您输入的原密码不正确，请重新输入");
         }else
         {
             $ret = db('user') ->where('user_id', $user_id) ->update($data);
             if(!$ret){
                $this->success("密码修改失败！");
             }
             else
             {
                $this->success("密码修改成功,请使用新密码重新登录",url('/frontend/login/logout'));

             }

         }

       }
    }

 }